﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApp.BLL;
using WebApp.BLL.Manage;
using WebApp.Common;
using WebApp.Models;
using WebApp.ViewModels;
using WebApp.Web.Core;
using WebApp.Web.Core.Auth;

namespace kzjd.rycp.WebApp.Areas.Basic.Controllers
{
    public class WorkMemberController : Controller
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger("WebApp.Log");

        #region List

        [AuthorizeFilter("Basic.WorkDept.Member")]
        public ActionResult List()
        {
            //编辑权限
            ViewBag.CanEdit = UserAuthBLL.HasAuth("Basic.WorkDept.Member");

            //科室下拉框数据
            ViewBag.DeptSelectList = new S_departmentService().GetSelectList(enmDeptType.Worker.ToString());

            return View();
        }

        #endregion

        #region 查询列表数据

        [AuthorizeFilter("Basic.WorkDept.Member")]
        public JsonResult MemberListJson(int page, int rows, string deptId, string s, string sort, string order)
        {
            var service = new S_dept_memberService();
            var deptservice = new S_departmentService();
            Dictionary<string, object> result = new Dictionary<string, object>();

            int rowscount = 0;

            string depttype = enmDeptType.Worker.ToString();

            var list = service.PageList(page, rows, depttype, deptId, s, sort, order, out rowscount).Select(p => new
            {
                p.Id,
                p.Sort,
                Deptname = deptservice.GetName(p.Dept_id),
                p.Name,
                p.Avatorurl,
                p.Job,
                p.Remark,
                Updatetime = CommonStr.GetDateTimeStr(p.Updatetime)
            });

            result.Add("total", rowscount);
            result.Add("rows", list);

            return Json(result);
        }

        #endregion

        #region 删除

        [AuthorizeFilter("Basic.WorkDept.Member")]
        public JsonResult Delete(string ids)
        {
            try
            {
                new S_dept_memberService().DeleteByIds(ids);

                return Json(new AjaxResult("0", "删除成功！"));
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return Json(new AjaxResult(AjaxResult.RESULT_ERROR, ex.Message));
            }
        }

        #endregion

        #region 保存

        [AuthorizeFilter("Basic.WorkDept.Member")]
        public JsonResult Save(string jsondata)
        {
            try
            {
                var deptservice = new S_dept_memberService();

                //序列化Json数据
                JsonDataModel model = Newtonsoft.Json.JsonConvert.DeserializeObject<JsonDataModel>(jsondata);

                var member = new S_dept_member();
                if (model.Id > 0)
                {
                    member = deptservice.Find(model.Id);
                }
                //通过反射给属性赋值
                model.SetModelData<S_dept_member>(member, true);

                //保存
                deptservice.Save(member);

                return Json(new AjaxResult(AjaxResult.RESULT_OK, "保存成功！"));
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return Json(new AjaxResult(AjaxResult.RESULT_ERROR, ex.Message));
            }
        }



        #endregion

        #region 编辑/查看

        [AuthorizeFilter("Basic.WorkDept.Member")]
        // GET: Manage/Role/Edit/5
        public ActionResult Edit(int id)
        {
            if (id == 0)
            {
                //科室下拉框数据
                ViewBag.DeptSelectList = new S_departmentService().GetSelectList(enmDeptType.Worker.ToString());

                return View(new S_dept_member()
                {
                    Dept_id = Utils.NvInt(Request.QueryString["dept"])
                });
            }
            else
            {

                var item = new S_dept_memberService().Find(id);

                if (item == null)
                {
                    throw new HttpException(404, "Member (id='" + id.ToString() + "') not found!");
                }

                //科室下拉框数据
                ViewBag.DeptSelectList = new S_departmentService().GetSelectList(enmDeptType.Worker.ToString(), item.Dept_id.ToString());

                return View(item);
            }
        }

        #endregion

        #region 上传文件

        /// <summary>
        /// 
        /// </summary>
        /// <param name="path">上传文件保存的子目录</param>
        /// <returns></returns>
        [IgnoreAuthorizeFilter]
        public JsonResult UploadFile()
        {
            string uploadroot = new S_environmentService().GetValue("upload.rootpath").TrimEnd('\\');

            //文件上传失败
            UploadResult result = new UploadResult();
            try
            {
                if (Request.Files.Count == 0)
                {
                    result.Ret = UploadResult.RESULT_ERROR;
                    result.Msg = "请选择文件！";
                    return Json(result);
                }

                //获取上传文件
                HttpPostedFileBase hpfFile = Request.Files[0];
                FileInfo fi = new FileInfo(hpfFile.FileName);
                //允许的文件类型
                string allowex = ".jpg;.jpeg;.png;.bmp;";
                if (!allowex.ToLower().Contains(fi.Extension.ToLower() + ";"))
                {
                    result.Ret = UploadResult.RESULT_ERROR;
                    result.Msg = "只能上传以下类型文件：" + allowex + "！";
                    return Json(result);
                }
                //验证文件大小(4M)
                int maxlength = 1024 * 1024 * 1;
                if (hpfFile.ContentLength > maxlength)
                {
                    result.Ret = UploadResult.RESULT_ERROR;
                    result.Msg = "文件不能超过1M！";
                    return Json(result);
                }

                //上传文件名
                string serverfilename = Guid.NewGuid().ToString().Replace("-", "") + fi.Extension;

                //文件物理目录
                string phfilepath =  "/avatar/";
                //文件物理目录
                if (!Directory.Exists(uploadroot + phfilepath))
                {
                    Directory.CreateDirectory(uploadroot + phfilepath);
                }
                //保存文件
                hpfFile.SaveAs(uploadroot + phfilepath + serverfilename);

                //文件上传成功
                result.Ret = UploadResult.RESULT_OK;
                //文件虚拟路径（URL）
                result.Fileurl = phfilepath + serverfilename;
                //原始文件物理路径
                result.Filename = hpfFile.FileName;
                return Json(result, "text/html");
            }
            catch (Exception ex)
            {
                log.Error(ex);
                result.Ret = UploadResult.RESULT_ERROR;
                result.Msg = ex.Message;
                return Json(result, "text/html");
            }
        }

        #endregion

        #region 图片文件流

        [IgnoreAuthorizeFilter]
        public ActionResult AvatarImage()
        {
            string tempfile = Utils.NvStr(Request["path"]);
            string uploadroot = new S_environmentService().GetValue("upload.rootpath");
            string filepath = uploadroot + tempfile.Replace("/", "\\");
            if (!System.IO.File.Exists(filepath))
            {
                filepath = Request.MapPath("/content/images/avatar.png");
                //return HttpNotFound();
            }

            return File(filepath, "image/jpeg");
        }

        #endregion

    }
}